<template>
  <div>
    <a-modal :title="formRelation.title" :width="1400" :visible="formRelation.visible" :footer="null" @cancel="close">
      <a-spin :spinning="stepLoading" tip="Loading...">
      <a-steps size="small" :current="3" status="error" style="margin-bottom:20px">
          <a-step title="当前结算总金额">
              <template slot="description">
                  <span class="nums">{{total.totalAmount}}</span>
              </template>
          </a-step>
          <a-step title="服务费金额">
              <template slot="description">
                    <span class="nums">{{total.serviceFeeTotalAmount}}</span>
              </template>
          </a-step>
          <a-step title="开票金额">
              <template slot="description">
                  <span class="nums">{{total.invoiceTotalAmount}}</span>
              </template>
          </a-step>
      </a-steps>

      <a-alert v-if="errorMsg" type="error" style="margin-bottom:10px;" show-icon>
        <label slot="message">
          {{errorMsg}}
          <a-button style="height: 0;" type="link" @click="detailVisible=true">查看人员详情</a-button>
        </label>
      </a-alert>
      
      <a-card>
        <template #title>
           <a-form-model :model="billForm" layout="inline" ref="billForm">
            <a-row :gutter="20" style="margin-bottom: 20px;">
              <a-col :span="9">
                <a-form-model-item label="支付通道" prop="payChannel" :rules="[{ required: true, message: '请选择支付通道!' }]">
                  <a-radio-group v-model:value="billForm.payChannel" @change="paySwit">
                    <a-radio v-for="(opt,index) in payChannelOptions" :key="index" :value="opt.payChannel">
                    {{opt.bankName}}
                    </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="结算批次名称" prop="settleBatchName" :rules="[{ required: true, message: '请输入结算批次名称!' }]">
                  <a-input :maxLength="16" v-model:value="billForm.settleBatchName" style="width:280px" placeholder="请输入结算批次名称、结算批次名称长度不能超出16个字符" />
                </a-form-model-item>
              </a-col>
              <a-col :span="7">
                <a-form-model-item label="人员名称">
                  <a-input placeholder="请输入人员名称" style="width:180px;margin-right:10px;" v-model="billForm.userName"/>
                  <a-button type="primary" icon="search" @click="loadTable(true)">查询</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
          <a-alert v-if="tis" show-icon type="success">
              <span slot="message">
                  {{tis}}<a style="margin-left:10px;" @click="clearKeys">清空</a>
              </span>
          </a-alert>
          <a-table 
            :columns="table.columns" 
            :pagination="table.pagination" 
            @change="handleTableChange"
            rowKey="id"
            :rowSelection="rowSelection"
            :data-source="table.loadData">
              <template slot="settleAmount" slot-scope="text, record">
                <a-input
                  v-if="record.editable" 
                  style="width: 100px;"
                  :value="text"
                  @change="e => handleChange(e.target.value, record.id, 'settleAmount')"
                  />
                <template v-else>
                 ¥ {{ text }}
                </template>
              </template>
              <span slot="action" slot-scope="text, record">
                <a v-if="!record.editable" @click="editAmount(record.id)">修改</a>
                <template v-if="record.editable">
                  <a v-if="record.editable" @click="saveAmount(record)">保存修改</a>
                  <a-divider type="vertical" />
                  <a v-if="record.editable" @click="loadTable(false)">取消修改</a>
                </template>
                <a-divider type="vertical" />
                <a-popconfirm
                    title="撤销后，该条数据返回人员明细列表。是否撤销？"
                    ok-text="撤销"
                    cancel-text="取消"
                    @confirm="revoke(record)">
                      <a>撤销</a>
                </a-popconfirm>
              </span>
          </a-table>
        </template>
      </a-card>
      
      <div class="custom-model-footer">
        <label style="margin-right:100px;float: right;">当前账户余额：
          <span style="color:#ff4d4f;font-size:28px;line-height: 1;">{{billForm.balance}}</span> 元</label>
              <a-button type="primary" 
              style="float: right"
        :disabled="settleState" 
        @click="sendsubmit">确认提交</a-button>
        <a-popover title="温馨提示">
          <template #content>
            <p style="width: 250px;">支付通道，结算批次名称，信息填写完整才能提交</p>
            <p style="width: 250px;">服务费扣除方式线上时，账户余额要大于开票金额，才能提交</p>
            <p style="width: 250px;">服务费扣除方式线下时、账户余额要大于结算总金额，才能提交</p>
            <p style="width: 250px;">列表中有已短信实名认证用户、当月累计金额超出上限、当前金额超出规定区间不能提交</p>
            <p style="width: 250px;">结算批次名称长度不能超出16个字</p>
          </template>
          <a-button type="link" style="float: left;" icon="question-circle">帮助</a-button>
        </a-popover>
        <a-button type="danger" style="float: left;" v-action:taskSettleRevokeListBtn icon="delete" @click="batchRevoke">批量撤销</a-button>
      </div>
      </a-spin>
    </a-modal>

    <a-modal :title="formRelation.innerOtherTitle" :width="500" :confirmLoading="submitLoading" :visible="formRelation.innerOtherVisible" @ok="submitParkVerify" @cancel="formRelation.innerOtherVisible=false">
      <p>生成结算单后，不能取消。是否确认生成？</p>
    </a-modal>

     <a-modal title="人员详情" :width="500" :visible="detailVisible" :footer="null" @cancel="detailVisible=false">
       <a-list :data-source="isData">
        <a-list-item slot="renderItem" slot-scope="item, index">
          <label style="color: #f50;">{{ item.text }}</label>
        </a-list-item>
      </a-list>
    </a-modal>

  </div>
</template>
<script>

import { mapGetters } from 'vuex'
import { 
    allQueryTaskSttleDetailedBillList,
    allGetTaskSttleBillIsOpenAccount,
    allEditTaskSttleBillAmount,
    allTaskSttleBillCancel,
    allQueryEnterpriseBalance,
    allSttleSendCode,
    allSttleBillSuccess
} from '@/api/manage/sttle'
import { 
    checkAmount,
    checkNum
} from '@/utils/util'
import {
    COLUMNS_STTLE_BILL_CMB,
    COLUMNS_STTLE_BILL_SEA,
} from './form'
export default {
  name: 'taskSttleBill',
  data () {
    return {
        formRelation:{
            title:'预结算人员名单',
            innerTitle:'短信验证',
            innerOtherTitle:'温馨提示',
            visible:false,
            innerVisible:false,
            innerOtherVisible:false
        },
        billForm:{
          balance:'',
          serviceFeeSettleMode:'',
          payChannel:'',
          settleBatchName:'',
          userName:''
        },
        payChannelOptions:[],
        isData:[],
        selectedRowKeys:[],
        selectedRows:[],
        tis:'',
        codeForm:{
          smsVerifiedCode:''
        },
        total:{
          totalAmount:0,
          invoiceTotalAmount:0,
          serviceFeeTotalAmount:0
        },
        table:{
          columns:COLUMNS_STTLE_BILL_CMB,
          loadData:[],
          pagination:{
            current:1,
            pageSize: 10,
            total:0,
            showSizeChanger: true,
					showQuickJumper: true,
            pageSizeOptions: ["10", "20", "50","500"],
            showTotal: total => `共有 ${total} 条数据`,
          }
        },
        errorMsg:'',
        detailVisible:false,
        submitLoading:false,
        stepLoading:false
    }
  },
  computed: {
    ...mapGetters(['userInfo','enterAccount','serviceFee']),
    settleState(){
      var flag = false;
      if( !this.billForm.settleBatchName || this.billForm.balance < 0){
        flag = true;
      }
      return flag;
    },
    rowSelection(){
        return {
            selectedRowKeys:this.selectedRowKeys,
            fixed:true,
            onChange:this.onSelectChange,
            onSelect:this.onSelectSingleChange
        }
    }
  },
  methods:{
    add(item){
      let {billForm,formRelation,total,codeForm} = this;
      for(var keys in billForm){
        billForm[keys] = '';
      }
      for(var keys in total){
        total[keys] = 0;
      }
      this.userName = '';
      this.payChannelOptions = [];
      codeForm.smsVerifiedCode = '';
      this.stepLoading = true;
      this.queryOpenAccount(item);
    },
    async queryOpenAccount(item){
      const parkId = item.parkId;
      const enterpriseId = item.enterpriseId;
      const {code,data} = await allGetTaskSttleBillIsOpenAccount(parkId,enterpriseId);
      if(data && data.length >=1){
        let arr = [];
        data.forEach(v=>{
          if(v.type === 1){
            let params = {};
            params.payChannel = v.payChannel;
            params.accountStatus = v.accountStatus;
            if(v.payChannel === 1){
              params.bankName = '招商银行'
            }else if(v.payChannel === 3){
              params.bankName = '支付宝到卡'
            }else if(v.payChannel === 4){
              params.bankName = '支付宝到户'
            }
            arr.push(params)
          }
        })
        this.payChannelOptions = arr;
        this.billForm.payChannel = arr.length >= 1 ? arr[0].payChannel : '';
        this.loadTable(true);
        this.queryBalance(this.billForm.payChannel);
        this.formRelation.visible = true;
      }
    },
    async loadTable(flag){
      if(flag){
        this.table.pagination.current = 1;
      }
      let params = {};
      params.payChannel = this.billForm.payChannel;
      params.userName = this.billForm.userName;
      params.taskId = this.$route.query.taskId;
      params.pageNum = this.table.pagination.current;
      params.pageSize = this.table.pagination.pageSize;
      const {code,data,invoiceTotalAmount,serviceFeeTotalAmount,totalAmount} = await allQueryTaskSttleDetailedBillList(params);
      this.stepLoading = false;
      if(code === '1'){
        this.table.loadData = data.content;
        this.table.loadData.forEach(v => {
          v.editable = false;
        });
        this.table.pagination.total = data.total || 0;
        this.total.totalAmount = totalAmount;
        this.total.invoiceTotalAmount = invoiceTotalAmount;
        this.total.serviceFeeTotalAmount = serviceFeeTotalAmount;
        if(data.total > 0){
          this.getAllTable(data.total);
        }
        if(data.total == 0){
          this.isData = [];
          this.errorMsg = '';
        }
      }
    },
    async getAllTable(total){
      let params = {};
      params.payChannel = this.billForm.payChannel;
      params.taskId = this.$route.query.taskId;
      params.userName = this.billForm.userName;
      params.pageNum = 1;
      params.pageSize = total;
      const {code,data} = await allQueryTaskSttleDetailedBillList(params);
      if(code === '1'){
        this.isData = [];
        this.errorMsg = '';
        data.content.forEach(v=>{
          if(v.feeRatioStatus == 2){
            let params = {};
            params.text = v.userName + '：服务费比例不在区间';
            this.isData.push(params);
          }
          if(v.amountLimitStatus == 2){
            let params = {};
            params.text = v.userName + '：结算金额超出单人单月最大限额';
            this.isData.push(params);
          }
        })
        if(this.isData.length > 0){
          this.errorMsg = '服务费比例或者结算金额超出单人单月限额';
        }
      }
    },
    handleTableChange(pagination){
        this.table.pagination.current = pagination.current;
        this.table.pagination.pageSize = pagination.pageSize;
        this.loadTable(false);
    },
    paySwit(e){
      const val = e.target.value;
      this.billForm.payChannel = val;
      this.loadTable(true);
      this.queryBalance(val);
    },
    async queryBalance(payType){
      let params = {
        taskId:this.$route.query.taskId,
        payChannel:payType
      }
      this.billForm.balance = 0;
      const {code,data} = await allQueryEnterpriseBalance(params);
      if(code === '1'){
        this.billForm.balance = data.balance;
      }
    },
    editAmount(id){
      const newData = [...this.table.loadData];
      const target = newData.filter(item => id === item.id)[0];
      if (target) {
          target.editable = true;
          this.table.loadData = newData;
      }
    },
    handleChange(value, id, column) {
      const newData = [...this.table.loadData];
      const target = newData.filter(item => id === item.id)[0];
      if (target) {
        target[column] = value;
        this.table.loadData = newData;
      }
    },
    async saveAmount(item){
      if(!checkAmount(item.settleAmount)){
          return this.$message.error('金额为整数、小数保留2位！');
      }
      item.payChannel = this.billForm.payChannel;
      const {code} = await allEditTaskSttleBillAmount(item);
      if(code === '1'){
        this.$message.success('操作成功');
        this.loadTable(false);
      }
    },
    async revoke(item){
      let params = {id:item.id}
      const {code} = await allTaskSttleBillCancel(params);
      if(code === '1'){
        this.$message.success('操作成功');
        this.loadTable(true);
      }
    },
    batchRevoke(){
      let that = this;
      if(this.selectedRowKeys.length == 0){
        return this.$message.error('请勾选撤销数据');
      }
      this.$confirm({
        title: '确认撤销?',
        async onOk() {
          let selectedRowKeys = that.selectedRowKeys.join(',');
          let params = {id:selectedRowKeys}
          const {code} = await allTaskSttleBillCancel(params);
          if(code === '1'){
            that.$message.success('操作成功');
            that.clearKeys();
            that.loadTable(true);
          }
        },
        onCancel() {
        },
      });
      
    },
    onSelectSingleChange(record, selected, selectedRows){
      if(!selected){
        this.selectedRows.splice(this.selectedRows.findIndex(item=>item.id===record.id),1);
      }
    },
    onSelectChange(selectedRowKeys, rows) {
      this.selectedRowKeys = selectedRowKeys;
      const arrayObject = this.selectedRows.concat(rows);
      for(let obj of arrayObject){
          let rowsIdx = this.selectedRows.map(v=>v.id);
          if(!rowsIdx.includes(obj.id)){
              this.selectedRows.push(obj);
          }
      }
      this.tis="已选择 "+selectedRowKeys.length+" 项";
      if(selectedRowKeys.length==0){
          this.clearKeys();
      }
    },
    clearKeys(){
        this.tis="";
        this.selectedRowKeys = [];
        this.selectedRows = [];  
    },
    sendsubmit(){
      this.submitLoading = false;
      this.formRelation.innerOtherVisible = true;
    },
    async submitParkVerify(){
      let params = {};
      params.payChannel= this.billForm.payChannel;
      params.settleBatchName= this.billForm.settleBatchName;
      params.taskId = this.$route.query.taskId;
      this.submitLoading = true;
      const {code,data} = await allSttleBillSuccess(params);
      this.submitLoading = false;
      if(code === '1'){
        this.$message.success('操作成功');
        this.formRelation.visible = false;
        this.formRelation.innerOtherVisible = false;
        this.$emit("on-ok");
      }
    },
    close(){
      this.formRelation.visible = false;
      this.$emit("on-ok");
    }
  }
}
</script>
<style>
  .bg-red{
    background: #fff2f0 !important;
  }
  .ant-table-tbody > tr.bg-red > td{
    border-bottom:1px solid #ffccc7 !important;
  }
  .custom-model-footer{
    overflow: hidden;
    padding-top: 20px;
  }
</style>